package hamdler

import (
	"app-uploader/cache"
	"app-uploader/models"
	"github.com/gin-gonic/gin"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	num := c.PostForm("num")
	comment := c.PostForm("comment")
	if name == "" || num == "" || comment == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.App{
		Name:    name,
		Num:     num,
		Comment: comment,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "app_add"
	cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	var app []models.App
	models.DB.Find(&app)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": app,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var app models.App
	err := models.DB.Where("id=?", id).Find(&app).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": app,
	})
	return
}
